package com.pkk.penguin.frame.know.java.Javacoreknowledge.lock;

/**
 * @description: 锁对象
 * @author: peikunkun
 * @create: 2020-01-13 17:34
 **/
public class LockVo {

  private Object lockObj = new Object();

  private static Object lockStaticObj = new Object();

  /**
   * 名称
   */
  private transient Type method;

  public LockVo() {
  }

  public LockVo(Type method) {
    this.method = method;
  }

  public void run() {
    switch (method) {
      case lock:
        lock();
        break;
      case innerLock:
        innerLock();
        break;
      case staticLock:
        staticLock();
        break;
      case innerObjLock:
        innerObjLock();
        break;
      case staticInnerLock:
        staticInnerLock();
        break;
      case staticInnerObjLock:
        staticInnerObjLock();
        break;
      default:
        break;
    }
  }


  public void common() {
    deadLock();
  }

  public static void staticCommon() {
    staticDeadLock();
  }


  /**
   * @Description: 锁的简单实现
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/1/13 0013 下午 5:58
   */
  public synchronized void lock() {
    deadLock();
  }


  public void innerLock() {
    synchronized (LockVo.class) {
      deadLock();
    }
  }

  public void innerObjLock() {
    synchronized (lockObj) {
      deadLock();
    }
  }


  /**
   * @Description: 静态锁
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/1/16 0016 下午 2:11
   */
  public synchronized static void staticLock() {
    staticDeadLock();
  }


  public static void staticInnerLock() {
    synchronized (LockVo.class) {
      staticDeadLock();
    }
  }

  public static void staticInnerObjLock() {
    synchronized (lockStaticObj) {
      staticDeadLock();
    }
  }


  /**
   * @Description: 死锁方法
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/1/16 0016 下午 2:13
   */
  private static void staticDeadLock() {
    while (true) {
      try {
        Thread.sleep(1000L);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName() + " is hold the lock - ");
    }
  }

  /**
   * @Description: 死锁方法
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/1/16 0016 下午 2:13
   */
  private void deadLock() {
    while (true) {
      try {
        Thread.sleep(1000L);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println(Thread.currentThread().getName() + " is hold the lock - ");
    }
  }


}
